package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和口味数据
     * @param dishDTO
     */

    @Transactional    //事务，配合启动类的，开启注解形式的事务管理注解
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表添加一条数据
        dishMapper.insert(dish);
        //返回主键,在dishMapper.xml文件中配置了返回主键，所以dish中dishiId就有了数值
        Long dishId=dish.getId();

        //向口口味表插入n条数据
        List<DishFlavor> flavors =  dishDTO.getFlavors();
        if(flavors==null|| flavors.isEmpty()){
                return;
        }
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorMapper.insertBatch(flavors);

    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否能够删除，如果有起售中的菜品不能删
        for (Long id : ids) {
         Dish dish=   dishMapper.getById(id);
         if(dish.getStatus()== StatusConstant.ENABLE){
                //菜品处于起售状态不能删除
             throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
         }
        }

        //如果有套餐关联不能删
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds!=null&&!setmealIds.isEmpty()){
            //不能删
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        }
        //如果可以删，删除菜品表中的数据
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //还要吧对应的口味表的数据删除
//            dishFlavorMapper.deleteByDishId(id);
//        }

        //优化代码，批量删除
        dishMapper.deleteByIds(ids);
        //批量删除口味数据
        dishFlavorMapper.deleteByDishIds(ids);

    }


    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //先查菜品数据
        Dish dish = dishMapper.getById(id);
        //然后查询口味
        List<DishFlavor> flavors= dishFlavorMapper.getByDishId(id);
        //封装
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }


    /**
     * 修改菜品数据和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish =new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //反正就是直接更新很麻烦，不知道它把口味怎么样了，直接删掉原来的口味，然后直接插入
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }


    @Override
    public void setDishStatus(Long id, Integer status) {
        //如果该菜品处于某套餐中，而且该套餐处于出售状态，则不允许将其处于停售状态

        //查询这个菜品是否在一个起售的套餐中
        if(status==0){
            Long count= setmealMapper.countByDishId(id);
            if(count!=0){
                throw new DeletionNotAllowedException(MessageConstant.DISH_IN_ON_SALE_SETMEAL);
            }
        }
        //满足上面的条件，修改状态
        dishMapper.setStatus(id,status);
    }





    /**
     * 根据分类id查询菜品
     *
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        //从数据库返回许多菜品
        List<DishVO>  dishVOs= dishMapper.getByCategoryId(categoryId);
        //返回数据
        return dishVOs;
    }


    /**
     * 根据分类id查询菜品和口味数据，起售状态的菜品
     *
     */

    //我自己写的，不是黑马给的代码
    @Override
    public List<DishVO> listWithFlavors(Long categoryId){
        int status=1;
        //查询起售中的菜品
      List<DishVO> list= dishMapper.getByCategoryIdWithStatus(categoryId,status);
      //为list中每个DishVO添加口味数据
        for (DishVO dishVO : list) {
         dishVO.setFlavors(dishMapper.getFlavorsByDishId(dishVO.getId()));
        }

        return list;

    }
}
